import { UploadOutlined , DownloadOutlined} from '@ant-design/icons';
import { ReactSortable } from "react-sortablejs";
import myMessage from "../../utils/message"
import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
import jQuery from 'jquery';
import clsx from 'clsx';
import { Checkbox, Modal, Upload, Button, Tooltip, message, Spin} from "antd";
import { useFormField } from "../../context/form-context";
import { useForm } from "../../context/metadata-context";
import cloneDeep from "lodash/cloneDeep";
import _extend from "lodash/extend";
import moment from "moment";
import "./index.css";
import { useSelections, useUpdate } from "ahooks";
import request from "../../utils/request";
import { openWin, isIE, buildUrl, formatNumber } from "../../utils";
import ntkoBrowser from "../../../../ntko/ntkobackground.min.js"
import { useInject } from '../../context/inject-context';
import { checkInFile, updateFile } from './fileUtilis'; 
import eventBus, { useSubscribe } from '../../eventBus';
import { getFileIcon, filePreview, canFileEdit, isSafari, fileEdit, checkoutAndEdit, fileDownload, deleteFile } from './fileUtilis';
import { parseToArray } from '../../utils';

export default function FileItem ({
  file,
  fileListCurrent,
  isSelected,
  toggle,
  isDisplay,
  cell,
  fileTypeKey,
  updater,
  params,
  form,
  csrfToken,
  tplData,
  urlPrefix,
  fileIdList,
  fieldConfig,
  mode//Print 当前为打印模式
}) {

  let safari = isSafari();

  //附件注册签入事件，用于ntko编辑页面签入附件后，联动更新审批页面的附件签入
  let messageKey = "ntkoCheckinFile.update." + file.id;
  useSubscribe(messageKey, (data)=>{
    checkInFile({
      file:{
        id: data.id
      },
      mytype: "checkin",
      updater: updater,
      params: params,
      form: form,
      fileListCurrent: fileListCurrent
    });
  });

  return <div className="relative overflow-hidden transition-all duration-500 list-drag-con" id={file.id} key={file.id}>
          {fileListCurrent.__isAllDownload__ && (
            <span className="float-left">
              <Checkbox 
                name="选择附件" 
                disabled={file.show_uploading}
                checked={isSelected(file.id)} 
                onClick={() => toggle(file.id)}></Checkbox>
            </span>
          )}
          <div className="relative z-10 overflow-hidden name-wen text-sm">
            <i data-des="附件图标" className={"iconfont float-left " + getFileIcon(file.name)}></i>

            {
              mode === "Print"
              ? <span
                  className="name-span cursor-text op-preview pl-6px pr-6px"
                  id="opFileId"
                  file-id={file.id}
                  file-is_print={file.is_print ? 1 : 0}
                  file-is_download={file.is_download ? 1 : 0}
                >
                  <FileInfo file={file}></FileInfo>
                </span>
              : <Tooltip 
                  des="附件名称&上传人信息"
                  getPopupContainer={() => document.querySelector(".main-content")} 
                  color="white"
                  overlayClassName="mytip" 
                  placement="bottomLeft" 
                  title={<FileNameTip file={file}></FileNameTip>}>
                    <span
                      className="name-span text-color-link cursor-pointer op-preview pl-6px pr-6px"
                      id="opFileId"
                      file-id={file.id}
                      file-is_print={file.is_print ? 1 : 0}
                      file-is_download={file.is_download ? 1 : 0}
                      onClick={() => {
                        filePreview({
                          params: params,
                          tplData: tplData,
                          file: file
                        })
                      }}
                    >
                      <FileInfo file={file}></FileInfo>
                    </span>
                </Tooltip>
            }

            <div className="name-up text-777">
              {
                /*签出信息 */
                (file.LockedUser && !isDisplay && (file.is_checkout_and_edit || file.is_edit) )
                && <span className="checkTip bg-white hover-hide">{file.LockedUser}</span>
              }

              {
                (!isDisplay && cell.is_upload && !file.show_uploading)
                && <i title="拖拽" className="ml-3 cursor-move iconfont icon-tuodong1 op-drag handle hover-show"></i>
              }

              {
                (!isDisplay && file.is_checkin)
                && <i title="签入" 
                    onClick={()=>{
                      checkInFile({
                        file: file,
                        typeKey: fileTypeKey,
                        updater: updater,
                        params: params,
                        form: form,
                        fileListCurrent: fileListCurrent,
                        csrfToken: csrfToken
                      })//签入
                    }}
                    className="ml-3 cursor-pointer iconfont icon-qianru op-checkin ico-label hover-show"
                    ></i>
              }

              {
                (
                  !isDisplay 
                  && file.is_edit 
                  && canFileEdit({
                      file: file,
                      tplData: tplData
                    })
                )
                && (
                  safari
                  ? <Tooltip 
                      getPopupContainer={() => document.querySelector(".main-content")} 
                      color="white"
                      overlayClassName="mytip" 
                      placement="bottomLeft" 
                      title={"Safari暂不支持编辑"}>
                        <i className="ml-3 cursor-pointer iconfont icon-bianji hover-show"></i>
                    </Tooltip>
                  : <i 
                      title='编辑'
                      onClick={()=>{
                        fileEdit({
                          tplData: tplData,
                          file: file,
                          urlPrefix: urlPrefix
                        });//编辑
                      }}
                      className="ml-3 cursor-pointer iconfont icon-bianji hover-show"></i>
                  )
              }

              {
                (
                  !isDisplay 
                  && file.is_checkout_and_edit 
                  && canFileEdit({
                        file: file,
                        tplData: tplData
                      })
                )
                && (
                  safari
                  ? <Tooltip 
                      getPopupContainer={() => document.querySelector(".main-content")} 
                      color="white"
                      overlayClassName="mytip" 
                      placement="bottomLeft" 
                      title={"Safari暂不支持签出&编辑"}>
                        <i className="ml-3 cursor-pointer iconfont icon-qianchubianji op-checkout-and-edit hover-show"></i>
                    </Tooltip>
                  : <i 
                      title="签出&编辑"
                      onClick={()=>{
                        checkoutAndEdit({
                          updater: updater,
                          file: file,
                          typeKey: fileTypeKey,
                          params: params,
                          form: form,
                          fileListCurrent: fileListCurrent,
                          tplData: tplData,
                          urlPrefix: urlPrefix
                        });//签出编辑
                      }}
                      className="ml-3 cursor-pointer iconfont icon-qianchubianji op-checkout-and-edit hover-show"></i>
                  )
              }

              {
                file.is_download 
                && <i className='iconfont float-left leading-26px ml-3 cursor-pointer op-download hover-show'>
                  <DownloadOutlined 
                    title="下载"
                    className='text-base'
                    onClick={() => {
                      fileDownload({
                        id: [file.id],
                        params: params,
                        tplData: tplData,
                        urlPrefix: urlPrefix
                      });
                    }}
                    file-id={file.id} /> 
                </i>
              }

              <DeleteBtn 
                file={file} 
                isDisplay={isDisplay} 
                tplData={tplData} 
                fileTypeKey={fileTypeKey}
                params={params}
                cell={cell}
                fileListCurrent={fileListCurrent}
                fileIdList={fileIdList}
                fieldConfig={fieldConfig}
                updater={updater}
              ></DeleteBtn>{/*删除*/}

              {
                //新上传附加的 对勾 提示
                (!isDisplay && file.is_new)
                && <i title="成功" className="icon-succeed iconfont icon-yishenpi"></i>
              }
              {
                //上传中显示loading
                file.show_uploading
                && <img src="/frontend/build/images/uploading.gif" className="uploading" />
              }
              {
                //上传中显示进度
                file.show_uploading
                && <span className="ml-2 text-xs progress-txt text-gray-999">{file.percent}%</span>
              }
              
            </div>
            

          </div>
          {
            //上传进度条
            file.show_uploading
            && <div className="z-20 progress-external">
                <div style={{"width": file.percent + "%"}} className="transition-all duration-500 progress-internal"></div>
              </div>
          }

        </div>   
}

//绑定一个全局方法给其他页面使用 argv1 附件id，ntko编辑页面，编辑完毕后，需要同步调用组件的签入
if(!window.UpdateFileModifiedInfo){
  window.UpdateFileModifiedInfo = function (argv1, argv2) {
    if(argv2 == "saveAndIn"){//保存并签入时，做签入操作
      eventBus.publish("ntkoCheckinFile.update." + argv1, {
        id: argv1
      });
    }
  }
}

//附件名称 + tag + 上传人
function FileInfo({
  file
}){
  return <>
          {file.name}
          <Tags file={file}></Tags> {/*附件标签*/}
          <UploadUser file={file}></UploadUser>{/*上传人*/}
        </>
}

//附件鼠标移入提示
function FileNameTip({file}){
  if(file.records){
      var _user_code = file?.records?.upload_user_code || "";//上传人code
      if(_user_code){
        _user_code = "（" + _user_code + "）";
      }
    return <ul className="text-xs file-tip">
            <li>
              <p className="user_title"><span className="text-color-999">上传人 : </span>{file.records.upload_user}{_user_code}</p>
            </li>
            <li>
              <p className="user_title"><span className="text-color-999">上传时间 : </span>{file.records.upload_time}</p>
            </li>
            {
              //存在已阅人信息
              //测试说没人也要显示
              // file.records.preview_users
              // &&
              <li>
                  <p className="user_title"> <span className="text-color-999">已阅 : </span> {file?.records?.preview_users}</p>
                </li>
            }
          </ul>
  }
  return <>{file.name}</>
}

//附件标签
function Tags({
  file
}){
  if(!file.tags){
    return null;
  }
  let tags = parseToArray(file.tags);
  if (tags && tags.length) {
    return <>
            {
              tags.map(function (tagItem, tagIndex) {
                return <FileTag key={tagIndex} tagItem={tagItem}></FileTag>;
              })
            }
            </>
  }else{
    return null;
  }
}

//附件标签
function FileTag({tagItem}){
  let $input = useRef(null);
  useLayoutEffect(()=>{
    if(tagItem.style){
      jQuery($input.current).attr("style", tagItem.style);//给标签添加样式
    }
  })
  return <span ref={$input} className="file-tag ml-4px">{tagItem.name}</span>
}

//返回上传人名称
function UploadUser({
  file
}){
  const metadataManager = useForm();
  if(metadataManager.mode === "Print"){
    //打印模式不展示上传人信息
    return null;
  }
  var _uploadName = file?.records?.upload_user || "";
  var _user_code = file?.records?.upload_user_code || "";
  if(_uploadName === ""){
    return null;
  }
  if(_user_code){
    _user_code = "（" + _user_code + "）";
  }
  return <span className="ml-1 text-color-a5a6aa">
            {_uploadName}
            {_user_code}
          </span>
}

//删除按钮
function DeleteBtn({
  file,
  isDisplay,
  tplData,
  fileTypeKey,
  params,
  cell,
  fileListCurrent,
  fileIdList,
  fieldConfig,
  updater
}){
  let DeleteBtn = null;
  if (!isDisplay) {//编辑模式
    let isnotSysFile = file.source === "流程中心" || tplData.businessFileDelControl;//不是业务系统附件
    if (file.is_delete) {
      DeleteBtn = <i 
                    className={clsx("op-delete cursor-pointer hover-show iconfont icon-x ml-3", (!isnotSysFile && "businessDelTip"))} 
                    title='删除'
                    onClick={()=>{
                      if(isnotSysFile){
                        deleteFile({
                          fileId: file.id,
                          typeKey: fileTypeKey,
                          showConfirm: true,//需要确认后删除
                          params: params,
                          cell: cell,
                          fileListCurrent: fileListCurrent,
                          fileIdList: fileIdList,
                          fieldConfig: fieldConfig,
                          updater: updater
                        })
                      }
                    }}
                    file-id={file.id}></i>

      if(isnotSysFile){//不是系统附件
      }else{//系统附件不许删除，并且要给提示
        DeleteBtn = <>
          <Tooltip 
            getPopupContainer={() => document.querySelector(".main-content")} 
            color="white"
            overlayClassName="mytip"
            placement="top" 
            title={"请在业务系统中删除附件！"}>
            {DeleteBtn}
          </Tooltip>
        </>
      }
    }
  }
  return DeleteBtn;
}